package org.bbelovic.devel.exercises;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

public class WeatherKata {

    private final String pathToFile;
    private LineEvaluator evaluator;
    private LineProcessor processor;

    public WeatherKata(final String pathToFile, final LineEvaluator evaluator, final LineProcessor processor) {
        this.pathToFile = pathToFile;
        this.evaluator = evaluator;
        this.processor = processor;
    }
    
    public String findSmallestSpread() {
        BufferedReader br = null;
        LineEvaluatorOutput output = new LineEvaluatorOutput(Integer.MAX_VALUE, "N/A");
        try {
            br = new BufferedReader(new FileReader(pathToFile));
            String line = null;
            while ((line = br.readLine()) != null) {
                final List<String> lineTokens = processor.processLine(line);
                final LineEvaluatorInput input = new LineEvaluatorInput(lineTokens, output.getCurrentLine(), output.getReferenceValue());
                output = evaluator.evaluate(input);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(br);
        }
        return output.getCurrentLine();
    }

    private void close(final Closeable br) {
        try {
            if (br != null) {
                    br.close();
                }
        }
        catch (IOException e) {
                e.printStackTrace();
        }
    }
    
    int computeDifference(final String inputLine) {
        final String [] tokens = inputLine.split("\\s+");
        if (tokens.length >= 3) {
            if (Pattern.matches("\\d+", tokens[1]) && Pattern.matches("\\d+", tokens[2])) {
                int max = Integer.parseInt(tokens[1]);
                int min = Integer.parseInt(tokens[2]);
                return max - min;
            }
        }
        return Integer.MAX_VALUE;
    }
    
//    public static void main(String[] args) {
//        final WeatherKata kata = new WeatherKata("/home/bbelovic/Downloads/weather.dat");
//        String smallest = kata.findSmallestSpread();
//        System.out.println(smallest);
//    }
}
